# Copyright (C) 2015 Yaowen HE
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# return whether the specified option is set within arguments
# usage: has_opt <name> <args>
has_opt () {
    local opt

    local name="$1"
    shift

    for opt in "$@"; do
        if [ "$opt" = "--" ]; then
            return 1
        fi

        if expr "$opt" : "--$name" > /dev/null; then
            return 0
        fi
    done

    return 1
}

# get the value of specified option from arguments
# usage: get_opt <name> <args>
get_opt () {
    local opt
    local value

    local name="$1"
    shift

    for opt in "$@"; do
        if [ "$opt" = "--" ]; then
            return 1
        fi

        if value=$(expr "$opt" : "--$name=\(.*\)"); then
            echo "$value"
            return 0
        fi
    done

    return 1
}

# return the sub-command from arguments
# usage: get_cmd <args>
get_cmd () {
    if [ $# -gt 0 ] && ! expr "$1" : "--[^-].*" > /dev/null; then
        echo $1
        return 0
    else
        return 1
    fi
}

# log message to a file
# usage: log_msg <logfile> <msg>
log_msg () {
    local logfile=$1
    local msg=$2

    echo [`date +'%Y-%m-%d %H:%M:%S'`] "$msg" >> $logfile
}

# initialize fmark environment
# usage: fmark_init <args>
fmark_init () {
    if has_opt "help" "$@"; then
        display_cmd_help
        exit
    fi

    source "$confdir"/fmark.conf

    dbfile=$(get_opt "dbfile" "$@" || echo "$profiledir"/places.sqlite)

    if [ ! -r "$dbfile" ]; then
        echo "database '$dbfile' not found nor readable" >&2
        exit 1
    fi
}

# query in database
# usage: query_db <sql> [opts]
query_db () {
    sql="$1"
    shift

    sqlite3 "$*" "$dbfile" "$sql"
}

# print colorized information
# usage: print_color <msg> <color>
print_color() {
    if [ ! -t 1 ]; then
        echo "$1"
        return 0
    fi

    local black="\033[01;30m"
    local red="\033[31m"
    local green="\033[32m"
    local yellow="\033[33m"
    local blue="\033[34m"
    local magenta="\033[35m"
    local cyan="\033[36m"
    local white="\033[37m"

    eval local format=\$$2
    echo -e "${format}${1}\033[0m"
}
